<?php


namespace App\Http\Controllers\Saas;


use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Model\Agent;
use App\Model\AgentAmountLog;
use App\Model\AgentCashLog;
use App\Model\AgentHasShop;
use App\Model\Device;
use App\Model\Order;
use App\Utils\Result;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AgentController extends Controller
{
    public function index(Request $request)
    {
        $query = Agent::query();
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $pid = $request->input('pid');
        $type = $request->input('type');
        $query->when($name, function($q) use ($name) {
            $q->where('name', 'like', "%{$name}%");
        });
        $query->when($type, function($q) use ($type) {
            $q->where('type', $type);
        });
        $query->when($mobile, function($q) use ($mobile) {
            $q->where('mobile', $mobile);
        });
        $query->when($pid, function($q) use ($pid) {
            $q->where('pid', $pid);
        });
        $query->whereNull('deleted_at');
        $query->with('parent');
        $query->withCount('cashLog');
        $query->withCount('amountLog');
//        $query->withCount('shop');
        $data = $query->latest()->paginate($pageSize, ['*'], 'page', $page);
        $data->getCollection()->transform(function ($agent) {
            if ($agent->parent) {
                // 假设parent代理的名称字段为name
                $agent->pid_name = $agent->parent->name;
            } else {
                $agent->pid_name = null;
            }
            return $agent;
        });
        foreach($data as &$v){
            if(!$v['pid']){
                $agents = Agent::query()->where('pid',$v['id'])->pluck('id')->toArray();
            }{
                $agents = [];
            }
            array_push($agents,$v['id']);
            $devices = Device::query()->where('agent_id',$agents)->pluck('id')->toArray();
            $v['device_count'] = count($devices);
//            $v['order_count'] = Order::query()->whereIn('device_id',$devices)
//                ->where('status',3)
//                ->where('recharge_status',3)
//                ->count();
//            $v['order_amount'] = 0;
//            $v['order_count'] = 0;
//            $v['order_amount'] = Order::query()->whereIn('device_id',$devices)
//                ->where('status',3)
//                ->where('recharge_status',3)
//                ->sum('pay_amt');
        }
        return Result::success(new PaginationCollection($data));
    }

    public function getOrder(Request $request)
    {
        $id = $request->input('id');
        $sp = Agent::query()->where('id',$id)->first();
        if (!$sp->pid) {
            $agents = Agent::query()->where('pid', $id)->pluck('id')->toArray();
            array_push($agents,$id);
            $devices = Device::query()->whereIn('agent_id', $agents)->pluck('id')->toArray();
        } else {
            $devices = Device::query()->where('agent_id', $id)->pluck('id')->toArray();
        }
        $data['order_count'] = Order::query()->whereIn('device_id', $devices)
            ->where('status', 3)
            ->where('recharge_status', 3)
            ->count();
        $data['order_amount'] = Order::query()->whereIn('device_id', $devices)
            ->where('status', 3)
            ->where('recharge_status', 3)
            ->sum('pay_amt');
        return Result::success($data);
    }

    /**获取所有1级经销商
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function parentList(Request $request){
        $query = Agent::query();
        $query->where('status',1);
        $query->where('pid' , 0);
        $data = $query->get();
        return Result::success($data);
    }

    public function getParent(Request $request){
        $id = $request->input('id');
        $query = Agent::query();
        $data = $query->where('id' , $id)->first();
        if($data->pid > 0){
            $res = [$data->pid,$data->id];
        }else{
            $res = [$data->id];
        }
        return Result::success($res);
    }

    public function allList(Request $request){
        $query = Agent::query();
        $query->where('status',1);
        $query->where('pid' , 0);
        $data = $query->select('id as value','name as label')->get();
        foreach($data as &$v){
            $v->children = $query = Agent::query()->where('pid',$v->value)
                ->select('id as value','name as label')->get();
        }
        return Result::success($data);
    }

    public function show($id)
    {
        $sp = Agent::query()->where('id',$id)->first(['id','name','mobile','status','rate',
            'pid','tel_no','search_type','service','type']);

        return Result::success($sp);
    }


    public function add(Request $request)
    {
        $data = $request->only([
            'name',
            'mobile',
            'password',
            'status',
            'rate',
            'tel_no',
            'search_type',
            'pid',
            'service',
            'type'
        ]);
        if (Agent::where('mobile', $data['mobile'])->count()) {
            return Result::error(401, '手机号已存在');
        }
        $sp = new Agent();
        if($data['rate'] > 0.6){
            return Result::error(1001,'分润比例不得超过百分之0.6');
        }
        $sp->fill($data);
        $sp->password = Hash::make($data['password']);
        $sp->save();
        return Result::success();
    }

    public function edit(Request $request, $id)
    {
        $data = $request->only([
            'name',
            'mobile',
            'password',
            'status',
            'rate',
            'tel_no',
            'search_type',
            'pid',
            'service',
            'type'
        ]);
        if (Agent::where('mobile', $data['mobile'])->where('id', '<>', $id)->count()) {
            return Result::error(401, '手机号已存在');
        }
        if($data['type']== 1 && $data['rate'] > 0.6){
            return Result::error(1001,'分润比例不得超过百分之0.6');
        }
        $sp = Agent::find($id);
        if (isset($data['password']) && $data['password']) {
            $sp->password = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }
        $sp->mobile = $data['mobile'];
        $sp->status = $data['status'];
        $sp->name = $data['name'];
        $sp->tel_no = $data['tel_no'];
        $sp->search_type = $data['search_type'];
        $sp->pid = $data['pid'];
        $sp->service = $data['service'];
        $sp->type = $data['type'];
        $sp->rate =$data['rate'];
        $sp->save();
        return Result::success();
    }

    public function addShop(Request $request)
    {
        $agentId = $request->input('agent_id');
        $shopId = $request->input('shop_id');
        $rate = $request->input('rate', 0);

        $existSP = AgentHasShop::query()->where(['shop_id' => $shopId, 'agent_id' => $agentId])->first();
        if ($existSP) {
            return Result::error(400, '已经关联商户了，请勿重复关联！');
        }

        $res = new AgentHasShop();
        $res->agent_id = $agentId;
        $res->shop_id = $shopId;
        $res->rate = $rate;
        $res->save();

        return Result::success();
    }

    public function editShop(Request $request)
    {
        $id = $request->input('id');
        $rate = $request->input('rate');
        AgentHasShop::where('id', $id)->update([
            'rate' => $rate
        ]);

        return Result::success();
    }

    public function delShop(Request $request)
    {
        $id = $request->input('id');
        AgentHasShop::where('id', $id)->delete();

        return Result::success();
    }

    public function agentHasShop(Request $request)
    {
        $query = AgentHasShop::query();
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $status = $request->input('status');
        $agentId = $request->input('agentId');

        $query->when($name, function($q) use ($name) {
            $q->whereHas('shop', function($q) use ($name) {
                $q->where('name', 'like', "%{$name}%");
            });
        });
        $query->when($mobile, function($q) use ($mobile) {
            $q->whereHas('shop', function($q) use ($mobile) {
                $q->where('mobile', $mobile);
            });
        });
        $query->when($status, function($q) use ($status) {
            $q->whereHas('shop', function($q) use ($status) {
                $q->where('status', $status);
            });
        });
        $query->when($agentId, function($q) use ($agentId) {
            $q->where('agent_id', $agentId);
        });
        $query->with('agent', 'shop', 'shop.agent');
        $data = $query->latest()->paginate($pageSize, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }

    public function amountLog(Request $request)
    {
        $page = $request->input('page', 1);
        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $keyword = $request->input('keyword');
        $query = AgentAmountLog::query();
        $query->when($keyword, function ($q) use ($keyword) {
            $q->whereHas('agent', function ($q) use ($keyword) {
                // 确保你已经在 Agent 模型中定义了 bank() 关联
                $q->where('mobile', 'like', "%{$keyword}%")
                ->orWhere('name', 'like', "%{$keyword}%");
            });
        });
        $data = $query->with(['agent'])
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }


    public function cashLog(Request $request)
    {
        $page = $request->input('page', 1);
        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $keyword = $request->input('keyword');
        $status = $request->input('status');
        $query = AgentCashLog::query();
        $query->when($keyword, function ($q) use ($keyword) {
            $q->whereHas('agent', function ($q) use ($keyword) {
                // 确保你已经在 Agent 模型中定义了 bank() 关联
                $q->whereHas('bank', function ($q) use ($keyword) {
                    $q->where('tel_no', 'like', "%{$keyword}%")
                        ->orWhere('card_name', 'like', "%{$keyword}%");
                });
            });
        });

        if ($status) {
            $query->where('status', $status);
        }

        $data = $query->with(['agent','agent.bank'])
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);

        return Result::success(new PaginationCollection($data));
    }
}
